package com.lijing.huffmanTree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Description 赫夫曼树
 * @title: HuffmanTree
 * @Author LiJing
 * @Date: 2021/2/235:18 下午
 * @Version 1.0
 */
public class HuffmanTree {
    private Node root;

    public static void main(String[] args) {
        int[] arr = {13,7,8,3,29,6,1};
        Node HuffmanRoot = creatHuffmanTree(arr);
        HuffmanTree huffmanTree = new HuffmanTree(HuffmanRoot);
        huffmanTree.preList();
    }

    public static Node creatHuffmanTree(int[] arr){
        /*
         * @Date: 2021/2/24 12:16 下午
         * Step 1: 遍历arr，将每一个元素构建成一个Node，并放入ArrayList
         */
        List<Node> nodes = new ArrayList<Node>();
        for (int value : arr) {
            nodes.add(new Node(value));
        }
        while (nodes.size() > 1){
            /*
             * @Date: 2021/2/24 12:18 下午
             * Step 2: 从小到大进行排序
             */
            Collections.sort(nodes);
            System.out.println(nodes);
            /*
             * @Date: 2021/2/24 12:22 下午
             * Step 3: 取出权值最小的二叉树节点
             */
            Node left = nodes.get(0);
            Node right = nodes.get(1);
            /*
             * @Date: 2021/2/24 12:26 下午
             * Step 4: 构建一颗新的二叉树
             */
            Node parrent = new Node(left.getValue()+ right.getValue());
            parrent.left = left;
            parrent.right = right;
            /*
             * @Date: 2021/2/24 12:28 下午
             * Step 5: 从ArrayList中删除处理过的二叉树
             */
            nodes.remove(left);
            nodes.remove(right);
            nodes.add(parrent);
        }
        return nodes.get(0);
    }

    public void preList(){
        if (root != null){
            root.preOrder();
        }else {
            System.out.println("HuffmanTree is empty!");
        }
    }

    public HuffmanTree(Node root) {
        this.root = root;
    }
}
